package com.hyper_yang.javase.fileAndIO;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.*;

public class CopyTest {

    @DisplayName("图片复制: ")
    @Test
    public void test1() throws IOException {
        // 1、创建输入流对象
        InputStream is = new FileInputStream("src/main/java/com/hyper_yang/javase/fileAndIO/srcImg/182501.png");

        OutputStream os = new FileOutputStream("src/main/java/com/hyper_yang/javase/fileAndIO/destImg/182501_copy.png");

        // 2、准备缓冲数组
        byte[] bytes = new byte[1024];

        int len = -1; // 记录有效字节数
        while ((len = is.read(bytes)) != -1) {
            // 写出
            os.write(bytes, 0, len);
        }

        // 3、释放资源
        os.close();

        is.close();
    }

    @DisplayName("异常处理: ")
    @Test // JDK 7之前必须这么写
    public void test2() {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、创建输入流对象
            is = new FileInputStream("src/main/java/com/hyper_yang/javase/fileAndIO/srcImg/182501.png");

            os = new FileOutputStream("src/main/java/com/hyper_yang/javase/fileAndIO/destImg/182501_copy.png");

            // 2、准备缓冲数组
            byte[] bytes = new byte[1024];

            int len = -1; // 记录有效字节数
            while ((len = is.read(bytes)) != -1) {
                // 写出
                os.write(bytes, 0, len);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                // 3、释放资源
                if (os!=null)
                    os.close();
                if (is!=null)
                    is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @DisplayName("异常处理2: ")
    @Test
    public void test()  {
        try(// 1、创建输入流对象
            InputStream is = new FileInputStream("src/main/java/com/hyper_yang/javase/fileAndIO/srcImg/182501.png");

            OutputStream os = new FileOutputStream("src/main/java/com/hyper_yang/javase/fileAndIO/destImg/182501_copy.png");
        ){
            // 2、准备缓冲数组
            byte[] bytes = new byte[1024];

            int len = -1; // 记录有效字节数
            while ((len = is.read(bytes)) != -1) {
                // 写出
                os.write(bytes, 0, len);
            }
            // 3、资源自动释放，不用自己写释放步骤
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
